def createDaemon(logfile='/tmp/xxx_daemon.log'):
    import os
    try:
        if os.fork() > 0:
            print 'started...'
            os._exit(0)
    except OSError, error:
        print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)
        os._exit(1)

    os.setsid()
    os.umask(0)

    try:
        pid = os.fork()
        if pid > 0:
            os._exit(0)
    except OSError, error:
        print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)
        os._exit(1)

    for fd in xrange(0, 1024):
        try:
            os.close(fd)
        except OSError:
            pass
    os.open(logfile, os.O_RDWR|os.O_CREAT)
    os.dup2(0, 1)
    os.dup2(0, 2)

if __name__ == '__main__':
    createDaemon()
